﻿using JVMTI_CONN_CONNECT;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace JVMTI_CORE_SHELL
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Startup : Window
    {
        public Startup()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Startup_Loaded);
        }


        async void Startup_Loaded(object sender, RoutedEventArgs e)
        {
            var fileName = "";
            if (UserPreference.Default.PreviousFile == "")
            {
                fileName = Directory.GetFiles(".", "*.orca").FirstOrDefault();
                if (fileName == null)
                {
                    show.Click += show_Click;
                    show.Visibility = Visibility.Visible;
                    return;
                }
            }
            else
            {
                fileName = (UserPreference.Default.PreviousFile);
            }
            var name = new FileInfo(fileName).FullName;
            name = name.Substring(0, name.LastIndexOf(".orca"));
            App.FileNameInUse = name;
            JvmtiEvents events = new JvmtiEvents();
            JvmtiEventCreationOptions option = new JvmtiEventCreationOptions(fileName);
            await Task.Run(() =>
                {
                    using (var streamReader = new StreamReader(File.Open(fileName, FileMode.Open)))
                    {
                        while (streamReader.EndOfStream == false)
                        {
                            var curr = new JvmtiEvent(streamReader.ReadLine(), option, App.FileNameInUse);
                            if(curr.MethodName != JvmtiMethodEnum.AgentLoaded && curr.MethodName != JvmtiMethodEnum.AgentUnload)
                            events.Add(curr);
                        }
                    }
                    events.Count();
                    Thread.Sleep(2000);
                });

            var threads = events.CreateThreadLifeCycleView();
            App.MaximumThreadEndTime = threads.Max<LifeCycleViewModel>(t => t.EndTimeStamp);
            App.MinimumStartTime = threads.Min<LifeCycleViewModel>(t => t.StartTimeStamp);
            MainWindow r = new MainWindow(events);
            r.title.Header = fileName;
            r.Show();
            this.Close();

        }

        void show_Click(object sender, RoutedEventArgs e)
        {
            App.RelaunchWithSelection(this);
        }
    }
}
